package com.naizhuai.ui.user.register;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.naizhuai.MainActivity;
import com.naizhuai.Model.AccountHelper;
import com.naizhuai.Model.ModelProvider;
import com.naizhuai.Model.db.user.PersonUserBean;
import com.naizhuai.Model.db.user.UserDataSourse;
import com.naizhuai.Model.db.user.UserRepository;
import com.naizhuai.R;
import com.naizhuai.network.NetWorkObserver;
import com.naizhuai.network.apistore.UserManageDataApiStore;
import com.naizhuai.network.apistore.apistoreiml.CommonManagerIml;
import com.naizhuai.network.exception.ValidateException;
import com.naizhuai.ui.components.CircleImageView;
import com.naizhuai.ui.components.swipeback.SwipeBackActivity;
import com.naizhuai.ui.entity.ImgBean;
import com.naizhuai.ui.entity.JumpBean;
import com.naizhuai.ui.entity.SendSms;
import com.naizhuai.ui.entity.management.CompanyBean;
import com.naizhuai.ui.entity.management.DepartmentBean;
import com.naizhuai.ui.user.UserLogin;
import com.naizhuai.ui.user.UserManageDataApiStoreIml;
import com.naizhuai.util.AlbumUtils;
import com.naizhuai.util.BitmapUtils;
import com.naizhuai.util.ConstantsPersonResources;
import com.naizhuai.util.ConstantsState;
import com.naizhuai.util.ViewUtils;
import java.io.File;
import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import rx.Observable;

public class RegisterActivity extends SwipeBackActivity {
    public static final int COUNTDOWM_FACTOR = 60;
    @BindView(R.id.ed_realname)
    EditText edRealname;
    @BindView(R.id.ed_email)
    EditText edEmail;
    @BindView(R.id.ed_phonenumber)
    EditText edPhonenumber;
    @BindView(R.id.ed_verification_code)
    EditText edVerificationCode;
    @BindView(R.id.tv_verification_code)
    TextView tvVerificationCode;
    @BindView(R.id.ed_password)
    EditText edPassword;
    @BindView(R.id.btn_register)
    Button btnRegister;
    private UserRepository mUserRepository;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUserRepository= ModelProvider.provideUserRepository();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_register;
    }

//    @OnClick(R.id.userlogo)
//    public void onUserlogoClicked() {
//        AlbumUtils.singleChoice(this)
//                  .subscribe(albumFile -> updateUserAvator(albumFile.getPath()));
//    }
//    private void updateUserAvator(String path) {
//        showWaitDialog(getString(R.string.data_uploading));
//        Observable.just(path)
//                .map(imagepath -> {
//                    Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
//                    File file = BitmapUtils.changeBitmap2File(bitmap, RegisterActivity.this, "temp.jpeg");
//                    return file.getPath();
//                })
//                .flatMap(imagepath -> UserManageDataApiStoreIml.getInstance().uploadImg(imagepath))
//                .subscribe(new NetWorkObserver<ImgBean>() {
//                    @Override
//                    protected void onFail(String errormsg) {
//                        shortToast(errormsg);
//                    }
//
//                    @Override
//                    protected void onSuccess(ImgBean result) {
//                        imageUrl=result.getImgUrl();
//                        ViewUtils.showImg(imageUrl,userlogo);
//                    }
//                });
//
//
//    }
    @OnClick(R.id.tv_verification_code)
    public void onTvVerificationCodeClicked() {
        if (TextUtils.isEmpty(ViewUtils.text(edPhonenumber))){
            shortToast(getString(R.string.please_phonenumber));
            return;
        }
        UserManageDataApiStoreIml.getInstance().sendSms(ViewUtils.text(edPhonenumber), SendSms.REGISTER_CODE)
                .subscribe(new NetWorkObserver<String>() {
                    @Override
                    protected void onFail(String errormsg) {
                        shortToast(errormsg);
                    }

                    @Override
                    protected void onSuccess(String result) {
                        if (ConstantsState.isResultOk(result)){
                             shortToast(getString(R.string.sendsms_alreaday)+ViewUtils.text(edPhonenumber));
                             startCountDown(tvVerificationCode);
                        }
                    }
                });
    }
    private void startCountDown(TextView view) {
        view.setEnabled(false);
        CountDownTimer timer = new CountDownTimer(COUNTDOWM_FACTOR * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                view.setText(getString(R.string.count_down_again_send, millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
                view.setEnabled(true);
                view.setText(getString(R.string.again_send));
            }
        };
        timer.start();
    }
    @OnClick(R.id.btn_register)
    public void onBtnRegisterClicked() {
        try {
             checkInput();
             userRegister();
        }catch (ValidateException e){
            shortToast(e.getMessage());
        }
    }

    private void userRegister() {
        UserManageDataApiStoreIml.getInstance().userRegister(ViewUtils.text(edRealname), ViewUtils.text(edPhonenumber),
                ViewUtils.text(edVerificationCode), ViewUtils.text(edPassword), ViewUtils.text(edEmail))
                .subscribe(new NetWorkObserver<UserLogin>() {
                    @Override
                    protected void onFail(String errormsg) {
                        shortToast(errormsg);
                    }

                    @Override
                    protected void onSuccess(UserLogin userLogin) {
                        saveUidSid(userLogin.getUid(), userLogin.getSid());
                        mUserRepository.updateLoginUser(new UserDataSourse.GetUserCallback() {
                            @Override
                            public void onUserLoaded(PersonUserBean user) {
                                jumpMain();
                                setShareValue(CompanyBean.COMPANY_NAME_KEY, user.getName());
                                setShareValue(CompanyBean.COMPANY_ID_KEY, user.getCompanyId());
                                setShareValue(DepartmentBean.DEPARTMENT_ID_KEY, user.getDepartmentId());
                                CommonManagerIml.getInstance().user_report(JPushInterface.getRegistrationID(getActivityContext()), JumpBean.login)
                                        .subscribe(new NetWorkObserver<String>() {
                                            @Override
                                            protected void onFail(String errormsg) {

                                            }
                                            @Override
                                            protected void onSuccess(String result) {

                                            }
                                        });
                            }

                            @Override
                            public void onDataNotAvailable() {

                            }
                        });
                    }
                });

    }

    private void jumpMain() {
        shortToast(getString(R.string.login_ok));
        Intent intent=new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    private void saveUidSid(String uid,String sid) {
        getSp().saveValue(PersonUserBean.USER_ID_KEY, uid);
        getSp().saveValue(ConstantsPersonResources.SESSION_ID_KEY, sid);
    }
    private void checkInput() throws ValidateException{
        if (TextUtils.isEmpty(ViewUtils.text(edRealname))){
           throw new ValidateException(getString(R.string.please_real_name));
        }
        if (TextUtils.isEmpty(ViewUtils.text(edPhonenumber))){
            throw new ValidateException(getString(R.string.please_phonenumber));
        }
        if (TextUtils.isEmpty(ViewUtils.text(edVerificationCode))){
            throw new ValidateException(getString(R.string.please_identifying_code));
        }
        if (TextUtils.isEmpty(ViewUtils.text(edPassword))){
            throw new ValidateException(getString(R.string.please_password));
        }
    }
}

